import axios from "axios";
import mpAdapter from "axios-miniprogram-adapter";
import {useTokenState} from "@/store/index";
axios.defaults.adapter = mpAdapter;
// import { useInfoStore } from "@/store/user";
// const useInfo = useInfoStore();
import {
	netConfig
} from "./net.config";
	const tokenState=useTokenState();//token状态
const {
	baseURL,
	contentType,
	requestTimeout,
	successCode
} = netConfig;
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
	baseURL: baseURL,
	// 超时（毫秒）
	timeout: requestTimeout,
});

//请求计数
let reqNum = 0;
// request拦截器
service.interceptors.request.use(
	(config) => {
		if (config.showLoading) {
			uni.showLoading({
				mask: true,
				title: "正在加载中....",
				icon: "dot",
			});
		}
		// 在请求发出之前进行一些操作，每次发出请求就 reqNum++
		reqNum++;
		// 是否需要设置 token
		// const isToken = config.isToken || false;
		// 是否需要防止数据重复提交
		const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
		if (
			!isRepeatSubmit &&
			(config.method === "post" || config.method === "put")
		) {
			const requestObj = {
				url: config.url,
				data: typeof config.data === "object" ?
					JSON.stringify(config.data) :
					config.data,
				time: new Date().getTime(),
			};
		}
		config.headers[
			"Authorization"
		] = uni.getStorageSync('token');
		// console.log("config:",config)
		return config;
		// if (isToken) {
		//   if (useInfo.userInfo.auth && useInfo.userInfo.auth.token) {
		//     config.headers[
		//       "Authorization"
		//     ] = `Bearer ${useInfo.userInfo.auth.token}`;
		//     return config;
		//   } else {
		//   }
		// } else {
		//   return config;
		// }
	},
	(error) => {
		Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(res) => {
		uni.hideLoading();
		// 接受请求后 reqNum--，判断请求所有请求是否完成
		reqNum--;
		if (reqNum <= 0) {
			// console.log('请求完毕')
		} else {
			// console.log('接口' + reqNum + '请求中')
		}
		// 获取错误信息
		if (res.data.code!==200) {
			uni.showToast({
				title: res.data.msg,
				icon: "none",
				duration: 2000,
			});
			return Promise.reject(res.data);
		} else {
			return res.data
		}
	},
	(error) => {
		let degree = 0;
		uni.hideLoading();
		let {
			message
		} = error;

		if (message == "Network Error") {
			message = "后端接口连接异常";
		} else if (message.includes("timeout")) {
			message = "系统接口请求超时";
		} else if (message.includes("Request failed with status code")) {
			let code = message.substr(message.length - 3);
			if (code == 401) {
				uni.setStorageSync('token', '');
				tokenState.getToken();
				return Promise.reject(error);
			} else {
				message = "系统接口" + code + "异常";
			}
		} else if (message.includes("oken")) {
			message = `该功能需要登录授权才能使用`;
			degree = 1;
		}
		uni.showModal({
			title: "提示",
			content: message,
			success: function(res) {
				if (res.confirm) {
					if (degree === 1) {
						uni.navigateTo({
							url: `/pages/logon/index`,
						});
					}
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});


		return Promise.reject(error);
	}
);

export default service;